package com.youthfilmic.yuejian.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
/**
 * @title OSS底层配置
 * @author dxywx
 * @instruction 主要是连接阿里云的OSS服务，提供上传文件的基本操作
 * */
public class OSSUtil {
	static final String accessKeyId = "Ry7wQH0HQzwq8Job";
	static final String accessKeySecret = "evA1Dxy3mBT7owvuErVO5xwoG4rSaq";
	static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
	//图片上传服务器
	public static final String imageServer = "http://image.youthfilmic.com/";
	//文件上传服务器
	public static final String fileServer = "http://uploads.youthfilmic.com/";
	
	private static OSSClient getClient(){
        OSSClient client = new OSSClient(endpoint,accessKeyId, accessKeySecret);
        return client;
	}
	
	
	
	public static void main(String[] args) throws FileNotFoundException {
		try {
			String result = saveImage("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ezlJRwHm53SEafQKeOLxnJyknnWXb9wV9d__SdesWigjJ-jh691r_IghGNLc1qoVMPGLvcndJCkiw1xo6yBocvZFA6QgB7FKZs2k0fo1Z_Q&media_id=1xP5cuVwyIkMPP2tTotlpRBFCnjHQzGKw_zTeItT5CcAh07szb8Ml3c2Vh22Hsjq" , "yuejian/user/img/" + SaveImageFromUrlThread.getRamdomName() + ".jpg");
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	
	/**
	 * @title 文件上传
	 * @author Dxywx
	 * @time 2015.5.31
	 * */
	public static String saveFile(MultipartFile file , String path) throws IOException{
		OSSClient client = getClient();
		InputStream content = file.getInputStream();
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(file.getSize());
		PutObjectResult result = client.putObject("uploadsfilmore", path , content, meta);
		//System.out.println(result.getETag());
		return fileServer + path;
	}
	
	
	public static String saveImage(MultipartFile image , String path) throws IOException{
		OSSClient client = getClient();
		InputStream content = image.getInputStream();
		ObjectMetadata meta = new ObjectMetadata();
        //meta.setContentType("image/jpeg");
		meta.setContentLength(image.getSize());
		PutObjectResult result = client.putObject("uploadsfilmore", path , content, meta);
		return imageServer + path;
	}
	
	
	public static String saveImage(File file, String path) throws IOException{
		OSSClient client = getClient();
		InputStream content = new FileInputStream(file);
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(file.length());
		PutObjectResult result = client.putObject("uploadsfilmore", path , content, meta);
		//System.out.println(result.getETag());
		return imageServer + path;
	}
	
	
	/**
	 * @title 保存远程图片
	 * @instruction 微信新用户登陆的时候保存用户的当前头像
	 * @author Dxywx
	 * @time 2015.5.5
	 * */
	public static String saveImage(String picUrl , String path) throws IOException{
		InputStream content = null;
        HttpURLConnection httpURLConnection = null;
        int size = 0;
        try
        {
            URL url = new URL(picUrl);
            if (url != null)
            {
                httpURLConnection = (HttpURLConnection) url.openConnection();// 打开链接
                // 设置连接网络的超时时间
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod("GET");
                int resposeCode = httpURLConnection.getResponseCode();
                if (resposeCode == 200)// 如果请求成功
                {
                    // 从服务器中获得一个输入流
                    content = httpURLConnection.getInputStream();
                    size = httpURLConnection.getContentLength();
                }
            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
		OSSClient client = getClient();
		ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType("image/jpeg");
		meta.setContentLength(size);
		PutObjectResult r= client.putObject("uploadsfilmore", path, content, meta);
        System.out.println(r.getETag());
		return imageServer + path;
	}




	/**
	 * @title 获取远程图片的输入流（用于保存远程图片）
	 * @instruction 获取输入流之后可以直接调用OSS的相应接口上传，解决微信头像用户更改后就失效的问题
	 * @author Dxywx
	 * @time 2015.5.5
	 * */
	public static InputStream getInputStream(String path)
    {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try
        {
            URL url = new URL(path);
            if (url != null)
            {
                httpURLConnection = (HttpURLConnection) url.openConnection();// 打开链接
                // 设置连接网络的超时时间
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setDoInput(true);
                //
                httpURLConnection.setRequestMethod("GET");
                int resposeCode = httpURLConnection.getResponseCode();
                if (resposeCode == 200)// 如果请求成功
                {
                    // 从服务器中获得一个输入流
                    inputStream = httpURLConnection.getInputStream();
                    httpURLConnection.getContentLength();
                }
            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return inputStream;
    }

}
